<?php
/**
 * *
 *  * ============================================================================
 *  * Created by PhpStorm.
 *  * User: Ice
 *  * 邮箱: ice@sbing.vip
 *  * 网址: https://sbing.vip
 *  * Date: 2019/9/19 下午3:53
 *  * ============================================================================.
 */
declare(strict_types=1);

namespace app\common\middleware;

use brand\logic\BrandHelper;
use brand\logic\Config;
use Closure;
use think\AddonService;
use think\facade\View;
use think\Request;
use think\Response;

/**
 * 插件中间件.
 */
class Addon
{
    /**
     * 插件中间件.
     *
     * @param Request $request
     * @param Closure $next
     *
     * @return Response
     */
    public function handle($request, Closure $next)
    {

        hook('addon_middleware', $request);

        $addon_name = $request->param('brand_addon');

        if ($addon_name){
            define("BRAND_ADDON_NAME", $addon_name);
            //app名称设置
            app()->http->name($addon_name.'/'.$request->param('brand_module'));
            //设置CURD
            BrandHelper::addonBrandTablesPath($addon_name);
            //引入公共方法
            if (is_file(AddonService::getAddonDir($addon_name).'common.php')){
                include_once AddonService::getAddonDir($addon_name).'common.php';
            }
            //模版路经
            View::config(['view_path'=>AddonService::getAddonDir($addon_name).$request->param('brand_module').DS.config('view.view_dir_name').DS]);
            //加在静态资源文件
            $js_path = '/static/addons/'.$addon_name.'/js/';
            if (is_dir(public_path().$js_path)){

                foreach (scandir(public_path().$js_path) as $js_file) {

                    if (in_array($js_file,['.','..'])) continue;

                    $js_mate = '<script src="'.$js_path.$js_file.'"></script>';

                    if (strpos($js_file,'from_') === 0){
                        Config::$add_from_script[] = $js_mate;
                    }elseif (strpos($js_file,'table_') === 0){
                        Config::$add_table_script[] = $js_mate;
                    }else{
                        Config::$add_script[] = $js_mate;
                    }

                }

            }


            $css_path = '/static/addons/'.$addon_name.'/css/';
            if (is_dir(public_path().$css_path)){
                $add_style = [];
                foreach (scandir(public_path().$css_path) as $css_file) {
                    if (in_array($css_file,['.','..'])) continue;
                    $css_mate = '<link href="'.$css_path.$css_file.'" rel="stylesheet">';
                    $add_style[] = $css_mate;
                }
                if ($add_style) Config::$add_style = array_merge(Config::$add_style,$add_style);
            }


        }


        return $next($request);
    }
}
